home *** CD-ROM | disk | FTP | other *** search
/ CD ROM Paradise Collection 4 / CD ROM Paradise Collection 4 1995 Nov.iso / program / swagg_m.zip / MATH.SWG / 0043_Pascal Triangle.pas < prev    next >
Pascal/Delphi Source File  |  1993-11-02  |  2KB  |  60 lines

  1. {
  2. LOU DUCHEZ
  3.  
  4. >Also, does anyone have anycode to do Pascal's Triangle?
  5.  
  6. The pattern is:
  7.  
  8.     1 1
  9.    1 2 1
  10.   1 3 3 1
  11.  1 4 6 4 1
  12.  
  13. where each element = the sum of the two above it.
  14.  
  15. Arrange it like this:
  16.  
  17. 0110     --  The zeros are needed so that the algorithm can process the 1's.
  18. 01210
  19. 013310
  20. 0146410
  21.  
  22. I'd have two Arrays: one shows the last row's figures, and the other holds
  23. the current row's figures.  Each "new" element (call the index "i") = the
  24. sum of "previous" element "i" + "previous" element "i - 1".
  25. }
  26.  
  27. Procedure CalcPascalRow(r : Word);      { which row to calculate }
  28.  
  29. Var
  30.   prows   : Array[0..1, 0..100] of Word;{ your two Arrays }
  31.   thisrow,
  32.   lastrow : Byte;                       { point to this row & last row }
  33.   i, j    : Word;                       { counters }
  34.  
  35. begin
  36.   lastrow := 0;                         { set up "which row is which" }
  37.   thisrow := 1;
  38.   prows[lastrow, 0] := 0;               { set up row "1": 0110 }
  39.   prows[lastrow, 1] := 1;
  40.   prows[lastrow, 2] := 1;
  41.   prows[lastrow, 3] := 0;
  42.   For j := 2 to r do
  43.   begin  { generate each "line" starting w/2 }
  44.     prows[thisrow, 0] := 0;
  45.     For i := 1 to j + 1 do
  46.     begin  { each "new" element = sum of "old" }
  47.       prows[thisrow, i] :=   { element + predecessor to "old" }
  48.         prows[lastrow, i] +  { element }
  49.         prows[lastrow, i - 1];
  50.     end;
  51.     prows[thisrow, j + 2] := 0;
  52.     lastrow := thisrow;                 { prepare For next iteration }
  53.     thisrow := (thisrow + 1) mod 2;
  54.   end;
  55.   For i := 1 to r + 1 do
  56.   { Write each element of desired line }
  57.     Write(prows[lastrow, i] : 4);
  58.   Writeln;
  59. end;
  60.